package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;

import com.bm.library.Info;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.srwl.easeui.utils.EaseUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.AudioChatActivity;
import com.srwl.mytx.activity.ForwardMessageActivity;
import com.srwl.mytx.activity.MainActivity;
import com.srwl.mytx.activity.PickLocationMapActivity;
import com.srwl.mytx.activity.RPTransferActivity;
import com.srwl.mytx.activity.SendSingleCouponActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.activity.VideoChatActivity;
import com.srwl.mytx.activity.VideoRecordActivityV3;
import com.srwl.mytx.adapter.MyMessageAdapter;
import com.srwl.mytx.contrack.ContactContrack;
import com.srwl.mytx.contrack.ContactContrackImpl;
import com.srwl.mytx.domain.CoinTransfer;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.BottomDialog;
import com.srwl.mytx.widget.ChatFileShowPageView;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.MyChatExtendMenu;
import com.srwl.redpacketui.ui.fragment.SendPacketBaseFragment;

import java.util.ArrayList;

public class ChatFragment extends BaseChatFragment implements MyChatExtendMenu.MyChatExtendMenuItemClickListener, ContactContrack.View {

    private static final String TAG = "ChatFragment";
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;
    static final int ITEM_TRANSFER = 15;
    static final int ITEM_LOCATION = 3;

    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;
    private static final int REQUEST_CODE_SEND_RED_PACKET = 16;
    private static final int REQUEST_CODE_SEND_TRANSFER = 17;
    private static final int REQUEST_CODE_FORWARD_MESSAGE = 18;
    private static final int REQUEST_CODE_RECORD_VIDEO = 19;

    private static final int ITEM_RED_PACKET = 16;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;
    private ContactContrack.Presenter presenter;

    @Override
    protected void setUpView() {
        super.setUpView();
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EaseUtils.isSingleActivity(getActivity())) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                }
                onBackPressed();
            }
        });
        //((EaseEmojiconMenu) inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData()); 大图表情，暂时注销

        setListItemClickListener();

        setPresenter(new ContactContrackImpl(this, getContext()));

        if (!Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())&&!Utils.isTempUser(targetUser) && !Helper.getInstance().isNormalContact(targetUser.getuId())) {//自己费临时用户，且对方不是临时联系人，且 联系人状态 不是双边联系人状态，就禁用输入框

            inputMenu.enable(false);
            inputMenu.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Contact contact = Helper.getInstance().getContact(targetUser.getuId());
                    if (contact != null) {
                        showRelationBrokenDialog(contact);
                    } else {
                        Log.e(TAG, "showRelationBrokenDialog: 联系人为空...........................");
                    }
                }
            });

        }
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (intent.getAction()) {
                    case Constant.ACTION_CONTACT_CHANGED:
                        Contact contact = Helper.getInstance().getContact(targetUser.getuId());
                        //判断当前联系人是否和我已经解除联系人关系
                        if (contact != null) {
                            targetUser = contact.getTargetUser();
                            if (TextUtils.equals(Constant.CONTACT_STATUS_MUTUAL, contact.getStatus())) {
                                inputMenu.enable(true);
                            } else {
                                inputMenu.enable(false);
                                inputMenu.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        showRelationBrokenDialog(contact);
                                    }
                                });
                            }
                        }
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANGED);
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
        // showGuide();

    }

    private void showRelationBrokenDialog(Contact contact) {

        ConfirmDialog dialog = new ConfirmDialog(getActivity(), "提示", "对方已经解除和你的联系人关系,现在发送重新添加请求？", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                if (presenter != null) {
                    presenter.addContact(contact, getString(R.string.default_invite_message));
                }
            }
        });
        dialog.show();
    }


    protected void registerExtendMenuItem() {

        super.registerExtendMenuItem();
        inputMenu.registerExtendMenuItem(R.string.attach_video, R.drawable.tx_chat_video, ITEM_VIDEO);
        inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.tx_chat_phone, ITEM_VOICE_CALL);
        inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.tx_chat_video_call, ITEM_VIDEO_CALL);
        inputMenu.registerExtendMenuItem(R.string.attach_red_packet, R.drawable.tx_chat_coupon, ITEM_RED_PACKET);
        inputMenu.registerExtendMenuItem(R.string.attach_transfer, R.drawable.tx_chat_transfer, ITEM_TRANSFER);
        inputMenu.registerExtendMenuItem(R.string.attach_location, R.drawable.tx_chat_location, ITEM_LOCATION);
        inputMenu.setExtendMenuItemClickListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_PICTURE_CHOOSE:
                    // sendImageMessage(Matisse.obtainResult(data), YWEnum.SendImageResolutionType.BIG_IMAGE);
                    //sendPicByUri(Matisse.obtainResult(data));
//                    List<String> pictures = Matisse.obtainPathResult(data);
//
//                    sendImageMessage(pictures);
                    break;
                case REQUEST_CODE_RECORD_VIDEO:
                    String videoPath = data.getStringExtra("videoPath");
                    sendVideoMessage(videoPath);
                    break;

                case REQUEST_CODE_SELECT_FILE: //send the file
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            sendFileByUri(uri);
                        }
                    }
                    break;

                case REQUEST_CODE_MAP:
                    double latitude = data.getDoubleExtra("latitude", 0);
                    double longitude = data.getDoubleExtra("longitude", 0);
                    String locationAddress = data.getStringExtra("address");
                    if (locationAddress != null && !locationAddress.equals("")) {
                        sendLocationMessage(latitude, longitude, locationAddress);
                    } else {
                        Toast.makeText(getActivity(), R.string.unable_to_get_loaction, Toast.LENGTH_SHORT).show();
                    }
                    break;

                case REQUEST_CODE_SEND_RED_PACKET:
                    Log.d(TAG, "红包支付完成");
                    Coupon coupon = data.getParcelableExtra("coupon");
                    coupon.setChatType(EaseConstant.CHATTYPE_SINGLE);
                    Message message = new Message();
                    message.setId(IDUtils.genOrderItemId());
                    message.setFromId(myId);
                    message.setType(Constant.C2C_MESSAGE);
                    message.setSubType(Constant.IM_TYPE_COUPON);
                    message.setContent(JSONObject.toJSONString(coupon));
                    conversation.sendMessage(message);

                    // }
                    break;
                case REQUEST_CODE_SEND_TRANSFER:
                    CoinTransfer transfer = data.getParcelableExtra("coinTransfer");
                    Message transferMessage = new Message();
                    transferMessage.setId(IDUtils.genOrderItemId());
                    transferMessage.setFromId(myId);
                    transferMessage.setType(Constant.C2C_MESSAGE);
                    transferMessage.setSubType(Constant.IM_TYPE_TRANSFER);
                    transferMessage.setContent(JSONObject.toJSONString(transfer));
                    conversation.sendMessage(transferMessage);
                    break;
                case REQUEST_CODE_FORWARD_MESSAGE:

                    showToast("转发消息完成");
                default:
                    break;
            }
        }

    }


    protected void setListItemClickListener() {
        messageListView.setItemClickListener(new MyMessageAdapter.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String userId) {
                if (TextUtils.equals(userId, UserProfileManager.getInstance().getLoginUserInfo().getuId())) {
                    return;
                }
                Intent intent = new Intent(getActivity(), UserProfileActivity.class);
                intent.putExtras(fragmentArgs);
                startActivity(intent);
            }

            @Override
            public void onUserAvatarLongClick(String username) {

            }

            @Override
            public void onResendClick(final Message message) {


                final ConfirmDialog dialog = new ConfirmDialog(getContext(), "提示", "重新发送该消息？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        resendMessage(message);
                    }
                });
                dialog.show();
            }

            @Override
            public void onBubbleLongClick(final Message message) {
                ArrayList<String> dialogItems = new ArrayList<>();

                switch (message.getSubType()) {
                    case Constant.IM_TYPE_IMAGE:
                    case Constant.IM_TYPE_AUDIO:
                    case Constant.IM_TYPE_VIDEO:
                    case Constant.IM_TYPE_GEO:
                        dialogItems.add(Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_FORWARD);
                        dialogItems.add(Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_DELETE);
                        break;
                    case Constant.IM_TYPE_TEXT:
                        dialogItems.add(Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_COPY);
                        dialogItems.add(Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_FORWARD);
                        dialogItems.add(Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_DELETE);
                        break;

                    case Constant.IM_TYPE_COUPON:
                    case Constant.IM_TYPE_TRANSFER:
                        dialogItems.add(Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_DELETE);
                        break;
                }

                BottomDialog bottomDialog = new BottomDialog(getActivity(), dialogItems);
                bottomDialog.show();
                bottomDialog.setListener(new BottomDialog.InteractionListener() {
                    @Override
                    public void onDialogItemViewClick(int position, String itemName) {
                        switch (itemName) {
                            case Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_COPY:
                                clipboard.setPrimaryClip(ClipData.newPlainText(null,
                                        message.getContent()));
                                break;
                            case Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_DELETE:
                                conversation.deleteMessage(message);
                                break;
                            case Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_FORWARD:
                                Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
                                intent.putExtra(Constant.EXTRA_INFO_FORWARD_MESSAGE, message);
                                startActivityForResult(intent, REQUEST_CODE_FORWARD_MESSAGE);
                                break;
                            case Constant.MESSAGE_LONG_CLICK_DIALOG_ITEM_RECALL:

                                break;
                        }
                    }
                });


            }

            @Override
            public boolean onBubbleClick(Message message) {

                //显示短视频
                // if (message.getSubType() == Constant.IM_TYPE_VIDEO) {

                //跳转到单独的一个视频播放页面
//                    String videoPath;
//                    String localFilePath = message.getLocalFilePath();
//                    if (TextUtils.isEmpty(localFilePath)) {
//                        videoPath = Helper.getInstance().getFilePath() + File.separator + message.getContent();
//                    } else {
//                        videoPath = localFilePath;
//                    }
//                    startActivity(new Intent(getActivity(), FullScreenVideoPlayActivity.class).putExtra("videoPath", videoPath));


                //return false;
                //  }

                return false;


            }

            @Override
            public void onImageOrVideoRowClick(int smallImagePosition, Info imageInfo) {

                hideSoftKeyboard();
                int currentBigImagePosition = initBigImageData(smallImagePosition);
                if (!photosView.isInit()) {
                    photosView.init(imageMessageList, hasNotch, new ChatFileShowPageView.InteractionListener() {
                        @Override
                        public void onPageChange(int position) {
                            //大图对应的Message在信息列表中的位置、索引
                            Integer seekItemIndex = bigImageIndexMappingSmallImageIndex.get(position);
                            if (seekItemIndex != null) {
                                messageListView.scrollItemVisible(seekItemIndex);

                            } else {
                                Log.d(TAG, "onPageChange: 找不到 大图对应的Message在聊天消息列表中的索引");
                            }
                        }

                        @Override
                        public Info onGetImageRectInfo(int position) {
                            Integer seekItemIndex = bigImageIndexMappingSmallImageIndex.get(position);
                            if (seekItemIndex != null) {
                                return messageListView.getImageInfo(seekItemIndex);
                            } else {
                                Log.d(TAG, "onPageChange: 找不到 大图对应的Message在信息列表中的索引");
                            }
                            return null;
                        }
                    });
                }
                photosView.showBigPictures(currentBigImagePosition, imageInfo);
            }
        });
    }

    public void onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
            case ITEM_VIDEO:
                // TODO: 2019/6/13 录制小视频
                // ShortVideoKitProcesser.onShortVideoReplyBarItemClick(getActivity(), ChatFragment.this, handler, conversation);

                long SDCardRemainMB = FileUtils.getSDFreeSize();
                if (SDCardRemainMB >= 0L && SDCardRemainMB < 2L) {
                    showToast(getString(R.string.aliwx_no_enough_sdcard_size));
                    return;
                }


                //ShortVideoKitProcesser.showRecordShortVideo(PublishTopicActivity.this, null, REQUEST_CODE_RECORD_VIDEO, SITUATION_FOR_PUBLISH, "high", 0, 0);//阿里百川短视频录制
                //startActivityForResult(new Intent(getActivity(), VideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
                // startActivityForResult(new Intent(this, FFmpegVideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
                VideoRecordActivityV3.startActivity(this, REQUEST_CODE_RECORD_VIDEO);

                break;
            case ITEM_VOICE_CALL:
                startVoiceCall();
                break;
            case ITEM_VIDEO_CALL:
                startVideoCall();
                break;
            case ITEM_LOCATION:
                startActivityForResult(new Intent(getActivity(), PickLocationMapActivity.class), REQUEST_CODE_MAP);
                break;
            case ITEM_TRANSFER:

                Intent intent1 = new Intent(getActivity(), RPTransferActivity.class);
                intent1.putExtra(SendPacketBaseFragment.ARGS_TARGET_USER, targetUser);
                startActivityForResult(intent1, REQUEST_CODE_SEND_TRANSFER);
                break;
            case ITEM_TAKE_PICTURE:
                choosePicture();
                break;
            //red packet code : 进入发红包页面
            case ITEM_RED_PACKET:

                Intent intent = new Intent(getActivity(), SendSingleCouponActivity.class);
                intent.putExtra("targetId", chatTargetId);
                intent.putExtra("redPacketType", Constant.COUPON_TYPE_SINGLE);
                startActivityForResult(intent, REQUEST_CODE_SEND_RED_PACKET);
                break;
            default:
                break;
        }

    }

    private void choosePicture() {
//        Matisse.from(ChatFragment.this)
//                .choose(MimeType.ofImage())
//                .countable(true)
////                .capture(true)
////                .captureStrategy(
////                        new CaptureStrategy(true, "com.srwl.mytx.fileprovider"))
//                .maxSelectable(9)
//                // .addFilter(new (320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .forResult(REQUEST_CODE_PICTURE_CHOOSE);


        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setOriginalMenu(false, true, "")//显示 原图按键，默认不选择，表示 压缩发送
                .setCount(9)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        sendImageMessage(photos, isOriginal);
                    }
                });
    }

    /**
     * make a voice call
     */
    protected void startVoiceCall() {

        Helper.getInstance().setStartingCall(true);
        // startActivity(new Intent(getActivity(), VideoChatViewActivity.class).putExtras(bundle).putExtra("type", Constant.INVITE_TYPE_AUDIO_CALL));
        Intent intent = new Intent(getActivity(), AudioChatActivity.class);
        intent.putExtra(AudioChatActivity.ACTION, AudioChatActivity.CALLING);
        intent.putExtra("targetUserInfo", targetUser);
        startActivity(intent);
        inputMenu.hideExtendMenuContainer();
    }

    /**
     * make a video call
     */
    protected void startVideoCall() {

        Helper.getInstance().setStartingCall(true);
        Intent intent = new Intent(getActivity(), VideoChatActivity.class);
        intent.putExtra(VideoChatActivity.ACTION, VideoChatActivity.CALLING);
        intent.putExtra("targetUserInfo", targetUser);
        startActivity(intent);
        inputMenu.hideExtendMenuContainer();
    }


//    @Override
//    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//        if (!bol_fromChatActivity) {
//            if (oldBottom != 0 && bottom != 0 & oldBottom - bottom > 0) {
//                //软键盘弹出
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        titleBar.rl_topBar.setVisibility(View.GONE);
//                    }
//                });
//            } else if (oldBottom != 0 && bottom != 0 & bottom - oldBottom > 0) {
//                titleBar.rl_topBar.setVisibility(View.VISIBLE);
//            }
//        }
//    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        if (broadcastManager != null) {
            broadcastManager.unregisterReceiver(broadcastReceiver);
        }
    }

//    private void showGuide() {
//        Animation enterAnimation = new AlphaAnimation(0f, 1f);
//        enterAnimation.setDuration(800);
//        enterAnimation.setFillAfter(true);
//
//        Animation exitAnimation = new AlphaAnimation(1f, 0f);
//        exitAnimation.setDuration(600);
//        exitAnimation.setFillAfter(true);
//
//        //新增多页模式，即一个引导层显示多页引导内容
//        NewbieGuide.with(this)
//                .setLabel("chatFragment")//设置引导层标示区分不同引导层，必传！否则报错
////                .anchor(anchor)
//                .setOnGuideChangedListener(new OnGuideChangedListener() {
//                    @Override
//                    public void onShowed(Controller controller) {
//                        Log.e(TAG, "NewbieGuide onShowed: ");
//                        //引导层显示
//                    }
//
//                    @Override
//                    public void onRemoved(Controller controller) {
//                        Log.e(TAG, "NewbieGuide  onRemoved: ");
//                        //引导层消失（多页切换不会触发）
//                    }
//                })
//                .setOnPageChangedListener(new OnPageChangedListener() {
//
//                    @Override
//                    public void onPageChanged(int page) {
//                        //引导页切换，page为当前页位置，从0开始
//                        // Toast.makeText(getActivity(), "引导页切换：" + page, Toast.LENGTH_SHORT).show();
//                    }
//                })
//                // .alwaysShow(true)//是否每次都显示引导层，默认false，只显示一次
//                .addGuidePage(GuidePage.newInstance()
//                                .addHighLight(inputMenu.getPrimaryMenu().getButtonSetModeVoice(), HighLight.Shape.CIRCLE, 30)
//                                .setLayoutRes(R.layout.view_guide_voice_record, R.id.iv)//引导页布局，点击跳转下一页或者消失引导层的控件id
//                                .setOnLayoutInflatedListener(new OnLayoutInflatedListener() {
//                                    @Override
//                                    public void onLayoutInflated(View view, final Controller controller) {
////                                view.findViewById(R.id.textView).setOnClickListener(new View.OnClickListener() {
////                                    @Override
////                                    public void onClick(View v) {
////                                        controller.showPreviewPage();
////                                    }
////                                });
//                                    }
//                                })
//                                .setEverywhereCancelable(false)//是否点击任意地方跳转下一页或者消失引导层，默认true
//                                //.setBackgroundColor(getResources().getColor(R.color.transparent_black))//设置背景色，建议使用有透明度的颜色
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
//                )
//                .addGuidePage(//添加一页引导页
//                        GuidePage.newInstance()//创建一个实例
//                                .addHighLight(titleBar.getRightImage(), HighLight.Shape.CIRCLE, 30)//添加高亮的view
////                                .addHighLight(tvBottom,
////                                        new RelativeGuide(R.layout.view_relative_guide, Gravity.TOP, 100) {
////                                            @Override
////                                            protected void offsetMargin(MarginInfo marginInfo, ViewGroup viewGroup, View view) {
////                                                marginInfo.leftMargin += 100;
////                                            }
////                                        })
//                                .setLayoutRes(R.layout.view_guide_chat_menu)//设置引导页布局
//                                .setEnterAnimation(enterAnimation)//进入动画
//                                .setExitAnimation(exitAnimation)//退出动画
//                )
//
//                .show();//显示引导层(至少需要一页引导页才能显示)
//    }

    public void refreshMessageList() {
        messageListView.refresh();
    }

    @Override
    public void setPresenter(ContactContrack.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showToast(String message) {
        showToast_v1(message);
    }
}
